Telegram Group & Telegram Channel
🎯 Как настроить CORS в Spring Boot

Когда фронт и бэк живут на разных доменах — CORS становится головной болью. Но Spring Boot даёт достаточно способов это настроить — от простых аннотаций до централизованной фильтрации.

1️⃣ Минимальная настройка — через @CrossOrigin

Если нужно открыть доступ только к одному контроллеру или методу:
@CrossOrigin(origins = "https://example.com")
@RestController
public class ApiController {
@GetMapping("/data")
public String getData() {
return "OK";
}
}


Удобно для быстрого прототипа, но неудобно для масштабируемого решения.

2️⃣ Глобальная настройка через WebMvcConfigurer

Если CORS нужен везде, лучше использовать конфигурационный класс:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}


Даёт полный контроль. Можно задать разные правила для разных путей.

3️⃣ Настройка CORS через application.yml (Spring Cloud Gateway)

Если вы используете Gateway, настройка может быть ещё проще:
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "https://example.com"
allowedMethods:
- GET
- POST
allowedHeaders: "*"


Подходит, если CORS должен работать до попадания запроса в конкретный микросервис.

4️⃣ CORS + безопасность

Если CORS работает «через раз», возможно, его блокирует Spring Security. Добавьте .cors() в конфигурацию:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors() // 👈 Без этого CORS не заработает
.and()
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
}


5️⃣ Тестирование CORS

Проверьте через curl:
curl -H "Origin: https://example.com" \
-H "Access-Control-Request-Method: GET" \
-X OPTIONS http://localhost:8080/data -v


Ответ должен содержать заголовки:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET


📌 Не оставляйте allowedOrigins("*") в проде. Это дыра в безопасности. Нужно чётко указывать домены.

💬 Как вы обычно настраиваете CORS в своих микросервисах?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6615
Create:
Last Update:

🎯 Как настроить CORS в Spring Boot

Когда фронт и бэк живут на разных доменах — CORS становится головной болью. Но Spring Boot даёт достаточно способов это настроить — от простых аннотаций до централизованной фильтрации.

1️⃣ Минимальная настройка — через @CrossOrigin

Если нужно открыть доступ только к одному контроллеру или методу:

@CrossOrigin(origins = "https://example.com")
@RestController
public class ApiController {
@GetMapping("/data")
public String getData() {
return "OK";
}
}


Удобно для быстрого прототипа, но неудобно для масштабируемого решения.

2️⃣ Глобальная настройка через WebMvcConfigurer

Если CORS нужен везде, лучше использовать конфигурационный класс:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}


Даёт полный контроль. Можно задать разные правила для разных путей.

3️⃣ Настройка CORS через application.yml (Spring Cloud Gateway)

Если вы используете Gateway, настройка может быть ещё проще:
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "https://example.com"
allowedMethods:
- GET
- POST
allowedHeaders: "*"


Подходит, если CORS должен работать до попадания запроса в конкретный микросервис.

4️⃣ CORS + безопасность

Если CORS работает «через раз», возможно, его блокирует Spring Security. Добавьте .cors() в конфигурацию:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors() // 👈 Без этого CORS не заработает
.and()
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
}


5️⃣ Тестирование CORS

Проверьте через curl:
curl -H "Origin: https://example.com" \
-H "Access-Control-Request-Method: GET" \
-X OPTIONS http://localhost:8080/data -v


Ответ должен содержать заголовки:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET


📌 Не оставляйте allowedOrigins("*") в проде. Это дыра в безопасности. Нужно чётко указывать домены.

💬 Как вы обычно настраиваете CORS в своих микросервисах?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6615

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

The global forecast for the Asian markets is murky following recent volatility, with crude oil prices providing support in what has been an otherwise tough month. The European markets were down and the U.S. bourses were mixed and flat and the Asian markets figure to split the difference.The TSE finished modestly lower on Friday following losses from the financial shares and property stocks.For the day, the index sank 15.09 points or 0.49 percent to finish at 3,061.35 after trading between 3,057.84 and 3,089.78. Volume was 1.39 billion shares worth 1.30 billion Singapore dollars. There were 285 decliners and 184 gainers.

Библиотека джависта | Java Spring Maven Hibernate from nl


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA